
#import "NetworkRequest.h"
#import "JTCSM.h"
// 拼接字符串
static NSString *boundaryStr = @"--";   // 分隔字符串
static NSString *randomIDStr;           // 本次上传标示字符串


@implementation NetworkRequest

#pragma -
#pragma - Synchronous Post Request

- (void)SynchronousPostRequestWithURL:(NSString *)url dictionary:(NSDictionary *)dict resultBlock:(NetWorkRequestBlock)block
{
//    if ([self networkStateChange]) {
        number = 0;
        if ([NSJSONSerialization isValidJSONObject:dict])
        {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
            json  =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        //创建url
        NSURL *URLstr = [NSURL URLWithString:url];
        do{
            //第二步，创建请求
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:URLstr cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
            
            [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
            
            NSString *str = [NSString stringWithFormat:@"%@",json];
            
            NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
            
            [request setHTTPBody:data];
            
            //第三步，连接服务器
            NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
            
            NSString *requestTmp = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
            NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
            //系统自带JSON解析
            result = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
            if (result == nil) {
                isRequest = NO;
                number ++;
            }
            if (number >=5 || result != nil){
                isRequest = YES;
            }
            
            continue;
        }while (!isRequest);
        
        block(result);

    }
    

    
//}


//todo 未判断请求次数，返回空时会无限请求导致崩溃,此方法修改跟上面一样
- (void)SynchronousPostRequestWithURL:(NSString *)url className:(id)className resultBlock:(NetWorkRequestBlock)block
{
    isRequest = NO;
    //将对象转换成字典
    NSDictionary *dicty = [df getObjectData:className];
    if ([NSJSONSerialization isValidJSONObject:dicty])
    {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicty options:NSJSONWritingPrettyPrinted error:&error];
        NSString *strUrl =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSString *str = [strUrl stringByReplacingOccurrencesOfString:@"\n  " withString:@""];
        NSString *string = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
        json = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    }
    
    
    //创建url
    NSURL *URLstr = [NSURL URLWithString:url];
    do{
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:URLstr cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        
        [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
        
        NSString *str = [NSString stringWithFormat:@"data=%@",json];
        
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        [request setHTTPBody:data];
    
        //第三步，连接服务器
        NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSString *requestTmp = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        //系统自带JSON解析
        result = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
            if (result == nil) {
                isRequest = NO;
                number ++;
            }
           if (number >=5 || result != nil){
            isRequest = YES;
        }
        continue;
    }while (!isRequest);
    
    block(result);
    
}


#pragma mark　-- post Image to server

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}


- (void)postImageToserverWithURL:(NSString *)URL object:(NSDictionary *)object resultBlock:(NetWorkRequestBlock)block{
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"WebKitFormBoundaryOVmb2WfuE8zDGDCW";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    UIImage *imageNew=[object objectForKey:@"UIImagePickerControllerOriginalImage"];
    //得到图片的data
    //NSData* data = UIImagePNGRepresentation(image);
    //UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多.

    //得到图片的data
    //NSData* data = UIImagePNGRepresentation(image);
    //UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多.
    [self getimagewithIamge:imageNew apla:0.7];
    NSData *data = imagedata;
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [object allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"UIImagePickerControllerEditedImage"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[object objectForKey:key]];
        }
    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"file0\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
//    NSString *j = [NSString stringWithFormat:@"json=%@",[self dictionaryToJson:KUSERDEFAULTGET(KInfoKey)]];
//    [myRequestData appendData:[j dataUsingEncoding:NSUTF8StringEncoding]];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    //建立连接，设置代理
    [NSURLConnection connectionWithRequest:request delegate:self];
    self.block = block;
}

- (void)getimagewithIamge:(UIImage *)imageNew apla:(float)apla{
    imagedata = UIImageJPEGRepresentation( imageNew, apla);
    float length = [imagedata length]/1000;
    if (length>512) {
        apla-=0.1;
        [self getimagewithIamge:imageNew apla:apla];
        
    }
}

- (void)postFeiledToserverWithURL:(NSString *)URL object:(id)object filePath:(NSString *)filePath fileName:(NSString *)fileName resultBlock:(NetWorkRequestBlock)block{
    
         //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"WebKitFormBoundaryOVmb2WfuE8zDGDCW";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [object allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"UIImagePickerControllerEditedImage"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[object objectForKey:key]];
        }
    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"myfile\"; filename=\"boris.amr\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: file/amr\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    //建立连接，设置代理
    [NSURLConnection connectionWithRequest:request delegate:self];
    self.block = block;
}

//接收到服务器回应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //接受到会用的时候,创建一个可变的data 用于存储服务器传送过来的数据
    self.receiveData=[NSMutableData data];
    
}
//接到服务器  传送过来的数据  这个方法可能会执行多次(服务器发得数据比较大得时候  会分多次发送  我们会接受多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //拼接服务器发送过来的数据
    [self.receiveData appendData:data];
}

//数据接受完毕  或者 数据上传完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    result = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableLeaves error:nil];
//    NSString *str = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
//    [df dictionaryWithJsonString:str]
    self.block(result);
//    self.imageblock(self.receiveData);
    
}
//请求超时 或者 断网的情况 或 URL 有问题   会调用此方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//    self.errorblock(error);
    self.block(nil);
}

#pragma mark - 私有方法
- (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile
{
    NSMutableString *strM = [NSMutableString string];
    
    [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
    [strM appendFormat:@"Content-Disposition: form-data; name=\"myfile\"; filename=\"%@\"\n", uploadFile];
    [strM appendFormat:@"Content-Type: %@\n\n", mimeType];
    return [strM copy];
}

//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}



@end
